package io.geekidea.boot.materials.controller;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.geekidea.boot.auth.util.LoginUtil;
import io.geekidea.boot.common.PageDto;
import io.geekidea.boot.framework.response.ApiResult;
import io.geekidea.boot.materials.dto.MaterialsExcel;
import io.geekidea.boot.materials.dto.MaterialsUpdateDto;
import io.geekidea.boot.materials.entity.Materials;
import io.geekidea.boot.materials.query.MaterialsQuery;
import io.geekidea.boot.materials.service.MaterialsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.math3.ml.neuralnet.UpdateAction;


import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/materials")
@Tag(name="门店物料库管理")
public class MaterialsController {
    @Resource
    private MaterialsService materialsService;

    @PostMapping("/search")
    @Operation(summary = "搜索门店物料库",description = "按照多条件组合分页查询门店物料库数据列表")
    public ApiResult search(@RequestBody MaterialsQuery materialsQuery){
        Page<Materials> page = new Page<>(materialsQuery.getPage(), materialsQuery.getSize());
        Page<Materials> pageDto = materialsService.getMaterialsPageList(page, materialsQuery);
        PageDto<Materials> pageInfo = new PageDto<>(pageDto.getRecords(),pageDto.getTotal(),pageDto.getSize(),pageDto.getCurrent());
        return ApiResult.success(pageInfo);
    }

    @GetMapping("/get/{id}")
    @Operation(summary = "根据ID查询单条门店物料数据")
    public ApiResult getMaterialsById(@PathVariable(value = "id")String id){
        final  Materials materials = materialsService.getMaterialsId(id);
        return ApiResult.success(materials);
    }

    @GetMapping("/getMaterialsList/{numbers}")
    @Operation(summary = "根据numbers查询单条门店物料数据")
    public ApiResult getMaterialsList(@PathVariable(value = "numbers")String numbers){
        Materials materials = new Materials();
        materials.setNumbers(numbers);
        List<Materials> list = materialsService.getMaterialsList(materials);
        return ApiResult.success(list);
    }
    @GetMapping("/getMaterialsStoresIdList/{id}")
    @Operation(summary = "根据门店id查询所有该门店物料数据")
    public ApiResult getMaterialsList(@PathVariable(value = "id")Integer id){
        Materials materials = new Materials();
        materials.setStoresId(id);
        List<Materials> list = materialsService.getMaterialsList(materials);
        return ApiResult.success(list);
    }



//    @PostMapping("/add")
//    @Operation(summary = "添加门店物料信息")
//    public ApiResult addArea(@RequestBody MaterialsDto materialsDto){
//        materialsDto.setWarehousingTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
//        Materials materialsEntity=new Materials();
//        BeanUtil.copyProperties(materialsDto,materialsEntity);
//        materialsService.save(materialsEntity);
//        return ApiResult.success("添加门店物料数据成功！");
//    }


    @PostMapping("/update")
    @Operation(summary = "修改门店物料信息")
    public ApiResult updateArea(@Validated(value = {UpdateAction.class})@RequestBody MaterialsUpdateDto materialsUpdateDto) throws Exception {
        materialsUpdateDto.setUpdatedTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        materialsUpdateDto.setUpdatedBy(LoginUtil.getUsername());
        Materials materialsEntity=new Materials();
        BeanUtil.copyProperties(materialsUpdateDto,materialsEntity);
        materialsService.updateById(materialsEntity);
        return ApiResult.success("修改门店物料数据成功！");
    }


    //逻辑删除
    @GetMapping("/del/{id}")
    @Operation(summary = "物理删除门店物料数据",description = "根据id逻辑删除门店物料对应的列")
    public ApiResult del(@PathVariable Integer id){
        int count = materialsService.delById(id);
        if (count<0) {
            return ApiResult.success("删除失败");
        }
        return ApiResult.success("删除成功");

    }

    @PostMapping("/romove/{id}")
    @Operation(summary = "逻辑删除门店物料数据")
    public ApiResult removeArea(@PathVariable(value = "id")Integer id){
        materialsService.removeById(id);
        return ApiResult.success("删除门店物料数据成功！");
    }


    @PostMapping("/list")
    @Operation(summary = "查询门店物料所有基础数据")
    public ApiResult materialsList(){
        List<Materials> materialsList = materialsService.list();
        return ApiResult.success(materialsList);
    }

    @PostMapping("/getMaterials/{id}")
    @Operation(summary = "门店物料详情",description = "根据id查询门店物料详情")
    public ApiResult getMaterials(@PathVariable(value = "id")String id){
        Materials materials = materialsService.getMaterialsId(id);
        return ApiResult.success(materials);
    }

    @PostMapping("/download")
    @Operation(tags = "Post",description = "导出门店物料信息")
    public void download(@RequestBody MaterialsQuery materialsQuery, HttpServletResponse response){
        //WarehousentryQuery warehousentryQuery = new WarehousentryQuery();

        List<MaterialsExcel> list = materialsService.getDownloadList(materialsQuery);

        OutputStream outputStream = null;
        try {
            response.setCharacterEncoding("UTF-8");
            String excelName = URLEncoder.encode("materialsExcel_"+ LocalDateTime.now(), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + excelName + ".xlsx");
            // 以字节流的形式输出响应正文
            outputStream = response.getOutputStream();
            try (ExcelWriter excelWriter = EasyExcel.write(outputStream, MaterialsExcel.class).build()) {
                WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
                excelWriter.write(list,writeSheet);
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }

}
